sensible names, profiling
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
6
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
12
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
15
16 /**
17 * Class representing a MediaWiki article and history.
18 *
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
22 *
23 * @package MediaWiki
24 */
25 class Article {
26 /**#@+
27 * @access private
28 */
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
34 var $mId, $mTable;
35 var $mForUpdate;
36 var $mOldId;
37 var $mRevIdFetched;
38 var $mRevision;
39 /**#@-*/
40
41 /**
42 * Constructor and clear the article
43 * @param mixed &$title
44 */
45 function Article( &$title ) {
46 $this->mTitle =& $title;
47 $this->clear();
48 }
49
50 /**
51 * get the title object of the article
52 * @public
53 */
54 function getTitle() {
55 return $this->mTitle;
56 }
57
58 /**
59 * Clear the object
60 * @private
61 */
62 function clear() {
63 $this->mDataLoaded = false;
64 $this->mContentLoaded = false;
65
66 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
67 $this->mRedirectedFrom = $this->mUserText =
68 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
69 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
70 $this->mTouched = '19700101000000';
71 $this->mForUpdate = false;
72 $this->mIsRedirect = false;
73 $this->mRevIdFetched = 0;
74 }
75
76 /**
77 * Note that getContent/loadContent may follow redirects if
78 * not told otherwise, and so may cause a change to mTitle.
79 *
80 * @param $noredir
81 * @return Return the text of this revision
82 */
83 function getContent( $noredir ) {
84 global $wgRequest, $wgUser, $wgOut;
85
86 # Get variables from query string :P
87 $action = $wgRequest->getText( 'action', 'view' );
88 $section = $wgRequest->getText( 'section' );
89 $preload = $wgRequest->getText( 'preload' );
90
91 $fname = 'Article::getContent';
92 wfProfileIn( $fname );
93
94 if ( 0 == $this->getID() ) {
95 if ( 'edit' == $action ) {
96 wfProfileOut( $fname );
97
98 # If requested, preload some text.
99 $text=$this->getPreloadedText($preload);
100
101 # We used to put MediaWiki:Newarticletext here if
102 # $text was empty at this point.
103 # This is now shown above the edit box instead.
104 return $text;
105 }
106 wfProfileOut( $fname );
107 $wgOut->setRobotpolicy( 'noindex,nofollow' );
108 return wfMsg( 'noarticletext' );
109 } else {
110 $this->loadContent( $noredir );
111 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
112 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
113 $wgUser->isIP($this->mTitle->getText()) &&
114 $action=='view'
115 ) {
116 wfProfileOut( $fname );
117 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
118 } else {
119 if($action=='edit') {
120 if($section!='') {
121 if($section=='new') {
122 wfProfileOut( $fname );
123 $text=$this->getPreloadedText($preload);
124 return $text;
125 }
126
127 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
128 # comments to be stripped as well)
129 $rv=$this->getSection($this->mContent,$section);
130 wfProfileOut( $fname );
131 return $rv;
132 }
133 }
134 wfProfileOut( $fname );
135 return $this->mContent;
136 }
137 }
138 }
139
140 /**
141 This function accepts a title string as parameter
142 ($preload). If this string is non-empty, it attempts
143 to fetch the current revision text.
144 */
145 function getPreloadedText($preload) {
146 if($preload) {
147 $preloadTitle=Title::newFromText($preload);
148 if(isset($preloadTitle) && $preloadTitle->userCanRead()) {
149 $rev=Revision::newFromTitle($preloadTitle);
150 if($rev) {
151 return $rev->getText();
152 }
153 }
154 }
155 return '';
156 }
157
158 /**
159 * This function returns the text of a section, specified by a number ($section).
160 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
161 * the first section before any such heading (section 0).
162 *
163 * If a section contains subsections, these are also returned.
164 *
165 * @param string $text text to look in
166 * @param integer $section section number
167 * @return string text of the requested section
168 */
169 function getSection($text,$section) {
170
171 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
172 # comments to be stripped as well)
173 $striparray=array();
174 $parser=new Parser();
175 $parser->mOutputType=OT_WIKI;
176 $striptext=$parser->strip($text, $striparray, true);
177
178 # now that we can be sure that no pseudo-sections are in the source,
179 # split it up by section
180 $secs =
181 preg_split(
182 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
183 $striptext, -1,
184 PREG_SPLIT_DELIM_CAPTURE);
185 if($section==0) {
186 $rv=$secs[0];
187 } else {
188 $headline=$secs[$section*2-1];
189 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
190 $hlevel=$matches[1];
191
192 # translate wiki heading into level
193 if(strpos($hlevel,'=')!==false) {
194 $hlevel=strlen($hlevel);
195 }
196
197 $rv=$headline. $secs[$section*2];
198 $count=$section+1;
199
200 $break=false;
201 while(!empty($secs[$count*2-1]) && !$break) {
202
203 $subheadline=$secs[$count*2-1];
204 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
205 $subhlevel=$matches[1];
206 if(strpos($subhlevel,'=')!==false) {
207 $subhlevel=strlen($subhlevel);
208 }
209 if($subhlevel > $hlevel) {
210 $rv.=$subheadline.$secs[$count*2];
211 }
212 if($subhlevel <= $hlevel) {
213 $break=true;
214 }
215 $count++;
216
217 }
218 }
219 # reinsert stripped tags
220 $rv=$parser->unstrip($rv,$striparray);
221 $rv=$parser->unstripNoWiki($rv,$striparray);
222 $rv=trim($rv);
223 return $rv;
224
225 }
226
227 /**
228 * Return an array of the columns of the "cur"-table
229 */
230 function getContentFields() {
231 return $wgArticleContentFields = array(
232 'old_text','old_flags',
233 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
234 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
235 }
236
237 /**
238 * Return the oldid of the article that is to be shown.
239 * For requests with a "direction", this is not the oldid of the
240 * query
241 */
242 function getOldID() {
243 global $wgRequest, $wgOut;
244 static $lastid;
245
246 if ( isset( $lastid ) ) {
247 return $lastid;
248 }
249 # Query variables :P
250 $oldid = $wgRequest->getVal( 'oldid' );
251 if ( isset( $oldid ) ) {
252 $oldid = intval( $oldid );
253 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
254 $nextid = $this->mTitle->getNextRevisionID( $oldid );
255 if ( $nextid ) {
256 $oldid = $nextid;
257 } else {
258 $wgOut->redirect( $this->mTitle->getFullURL( 'redirect=no' ) );
259 }
260 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
261 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
262 if ( $previd ) {
263 $oldid = $previd;
264 } else {
265 # TODO
266 }
267 }
268 $lastid = $oldid;
269 }
270 return @$oldid; # "@" to be able to return "unset" without PHP complaining
271 }
272
273
274 /**
275 * Load the revision (including cur_text) into this object
276 */
277 function loadContent( $noredir = false ) {
278 global $wgOut, $wgRequest;
279
280 if ( $this->mContentLoaded ) return;
281
282 # Query variables :P
283 $oldid = $this->getOldID();
284 $redirect = $wgRequest->getVal( 'redirect' );
285
286 $fname = 'Article::loadContent';
287
288 # Pre-fill content with error message so that if something
289 # fails we'll have something telling us what we intended.
290
291 $t = $this->mTitle->getPrefixedText();
292
293 $noredir = $noredir || ($wgRequest->getVal( 'redirect' ) == 'no')
294 || $wgRequest->getCheck( 'rdfrom' );
295 $this->mOldId = $oldid;
296 $this->fetchContent( $oldid, $noredir, true );
297 }
298
299
300 /**
301 * Fetch a page record with the given conditions
302 * @param Database $dbr
303 * @param array $conditions
304 * @access private
305 */
306 function pageData( &$dbr, $conditions ) {
307 return $dbr->selectRow( 'page',
308 array(
309 'page_id',
310 'page_namespace',
311 'page_title',
312 'page_restrictions',
313 'page_counter',
314 'page_is_redirect',
315 'page_is_new',
316 'page_random',
317 'page_touched',
318 'page_latest',
319 'page_len' ),
320 $conditions,
321 'Article::pageData' );
322 }
323
324 function pageDataFromTitle( &$dbr, $title ) {
325 return $this->pageData( $dbr, array(
326 'page_namespace' => $title->getNamespace(),
327 'page_title' => $title->getDBkey() ) );
328 }
329
330 function pageDataFromId( &$dbr, $id ) {
331 return $this->pageData( $dbr, array(
332 'page_id' => intval( $id ) ) );
333 }
334
335 /**
336 * Set the general counter, title etc data loaded from
337 * some source.
338 *
339 * @param object $data
340 * @access private
341 */
342 function loadPageData( $data ) {
343 $this->mTitle->loadRestrictions( $data->page_restrictions );
344 $this->mTitle->mRestrictionsLoaded = true;
345
346 $this->mCounter = $data->page_counter;
347 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
348 $this->mIsRedirect = $data->page_is_redirect;
349 $this->mLatest = $data->page_latest;
350
351 $this->mDataLoaded = true;
352 }
353
354 /**
355 * Get text of an article from database
356 * @param int $oldid 0 for whatever the latest revision is
357 * @param bool $noredir Set to false to follow redirects
358 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
359 * @return string
360 */
361 function fetchContent( $oldid = 0, $noredir = true, $globalTitle = false ) {
362 if ( $this->mContentLoaded ) {
363 return $this->mContent;
364 }
365 $dbr =& $this->getDB();
366 $fname = 'Article::fetchContent';
367
368 # Pre-fill content with error message so that if something
369 # fails we'll have something telling us what we intended.
370 $t = $this->mTitle->getPrefixedText();
371 if( $oldid ) {
372 $t .= ',oldid='.$oldid;
373 }
374 if( isset( $redirect ) ) {
375 $redirect = ($redirect == 'no') ? 'no' : 'yes';
376 $t .= ',redirect='.$redirect;
377 }
378 $this->mContent = wfMsg( 'missingarticle', $t );
379
380 if( $oldid ) {
381 $revision = Revision::newFromId( $oldid );
382 if( is_null( $revision ) ) {
383 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
384 return false;
385 }
386 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
387 if( !$data ) {
388 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
389 return false;
390 }
391 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
392 $this->loadPageData( $data );
393 } else {
394 if( !$this->mDataLoaded ) {
395 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
396 if( !$data ) {
397 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
398 return false;
399 }
400 $this->loadPageData( $data );
401 }
402 $revision = Revision::newFromId( $this->mLatest );
403 if( is_null( $revision ) ) {
404 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
405 return false;
406 }
407 }
408
409 # If we got a redirect, follow it (unless we've been told
410 # not to by either the function parameter or the query
411 if ( !$oldid && !$noredir ) {
412 $rt = Title::newFromRedirect( $revision->getText() );
413 # process if title object is valid and not special:userlogout
414 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) ) {
415 # Gotta hand redirects to special pages differently:
416 # Fill the HTTP response "Location" header and ignore
417 # the rest of the page we're on.
418 global $wgDisableHardRedirects;
419 if( $globalTitle && !$wgDisableHardRedirects ) {
420 global $wgOut;
421 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
422 $source = $this->mTitle->getFullURL( 'redirect=no' );
423 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
424 return false;
425 }
426 if ( $rt->getNamespace() == NS_SPECIAL ) {
427 $wgOut->redirect( $rt->getFullURL() );
428 return false;
429 }
430 }
431 $redirData = $this->pageDataFromTitle( $dbr, $rt );
432 if( $redirData ) {
433 $redirRev = Revision::newFromId( $redirData->page_latest );
434 if( !is_null( $redirRev ) ) {
435 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
436 $this->mTitle = $rt;
437 $data = $redirData;
438 $this->loadPageData( $data );
439 $revision = $redirRev;
440 }
441 }
442 }
443 }
444
445 # if the title's different from expected, update...
446 if( $globalTitle ) {
447 global $wgTitle;
448 if( !$this->mTitle->equals( $wgTitle ) ) {
449 $wgTitle = $this->mTitle;
450 }
451 }
452
453 # Back to the business at hand...
454 $this->mContent = $revision->getText();
455
456 $this->mUser = $revision->getUser();
457 $this->mUserText = $revision->getUserText();
458 $this->mComment = $revision->getComment();
459 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
460
461 $this->mRevIdFetched = $revision->getID();
462 $this->mContentLoaded = true;
463 $this->mRevision =& $revision;
464
465 return $this->mContent;
466 }
467
468 /**
469 * Gets the article text without using so many damn globals
470 * Returns false on error
471 *
472 * @param integer $oldid
473 */
474 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
475 return $this->fetchContent( $oldid, $noredir, false );
476 }
477
478 /**
479 * Read/write accessor to select FOR UPDATE
480 */
481 function forUpdate( $x = NULL ) {
482 return wfSetVar( $this->mForUpdate, $x );
483 }
484
485 /**
486 * Get the database which should be used for reads
487 */
488 function &getDB() {
489 $ret =& wfGetDB( DB_MASTER );
490 return $ret;
491 #if ( $this->mForUpdate ) {
492 $ret =& wfGetDB( DB_MASTER );
493 #} else {
494 # $ret =& wfGetDB( DB_SLAVE );
495 #}
496 return $ret;
497 }
498
499 /**
500 * Get options for all SELECT statements
501 * Can pass an option array, to which the class-wide options will be appended
502 */
503 function getSelectOptions( $options = '' ) {
504 if ( $this->mForUpdate ) {
505 if ( is_array( $options ) ) {
506 $options[] = 'FOR UPDATE';
507 } else {
508 $options = 'FOR UPDATE';
509 }
510 }
511 return $options;
512 }
513
514 /**
515 * Return the Article ID
516 */
517 function getID() {
518 if( $this->mTitle ) {
519 return $this->mTitle->getArticleID();
520 } else {
521 return 0;
522 }
523 }
524
525 /**
526 * Returns true if this article exists in the database.
527 * @return bool
528 */
529 function exists() {
530 return $this->getId() != 0;
531 }
532
533 /**
534 * Get the view count for this article
535 */
536 function getCount() {
537 if ( -1 == $this->mCounter ) {
538 $id = $this->getID();
539 $dbr =& $this->getDB();
540 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
541 'Article::getCount', $this->getSelectOptions() );
542 }
543 return $this->mCounter;
544 }
545
546 /**
547 * Would the given text make this article a "good" article (i.e.,
548 * suitable for including in the article count)?
549 * @param string $text Text to analyze
550 * @return integer 1 if it can be counted else 0
551 */
552 function isCountable( $text ) {
553 global $wgUseCommaCount;
554
555 if ( NS_MAIN != $this->mTitle->getNamespace() ) { return 0; }
556 if ( $this->isRedirect( $text ) ) { return 0; }
557 $token = ($wgUseCommaCount ? ',' : '[[' );
558 if ( false === strstr( $text, $token ) ) { return 0; }
559 return 1;
560 }
561
562 /**
563 * Tests if the article text represents a redirect
564 */
565 function isRedirect( $text = false ) {
566 if ( $text === false ) {
567 $this->loadContent();
568 $titleObj = Title::newFromRedirect( $this->fetchContent() );
569 } else {
570 $titleObj = Title::newFromRedirect( $text );
571 }
572 return $titleObj !== NULL;
573 }
574
575 /**
576 * Returns true if the currently-referenced revision is the current edit
577 * to this page (and it exists).
578 * @return bool
579 */
580 function isCurrent() {
581 return $this->exists() &&
582 isset( $this->mRevision ) &&
583 $this->mRevision->isCurrent();
584 }
585
586 /**
587 * Loads everything except the text
588 * This isn't necessary for all uses, so it's only done if needed.
589 * @private
590 */
591 function loadLastEdit() {
592 global $wgOut;
593
594 if ( -1 != $this->mUser )
595 return;
596
597 # New or non-existent articles have no user information
598 $id = $this->getID();
599 if ( 0 == $id ) return;
600
601 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
602 if( !is_null( $this->mLastRevision ) ) {
603 $this->mUser = $this->mLastRevision->getUser();
604 $this->mUserText = $this->mLastRevision->getUserText();
605 $this->mTimestamp = $this->mLastRevision->getTimestamp();
606 $this->mComment = $this->mLastRevision->getComment();
607 $this->mMinorEdit = $this->mLastRevision->isMinor();
608 }
609 }
610
611 function getTimestamp() {
612 $this->loadLastEdit();
613 return wfTimestamp(TS_MW, $this->mTimestamp);
614 }
615
616 function getUser() {
617 $this->loadLastEdit();
618 return $this->mUser;
619 }
620
621 function getUserText() {
622 $this->loadLastEdit();
623 return $this->mUserText;
624 }
625
626 function getComment() {
627 $this->loadLastEdit();
628 return $this->mComment;
629 }
630
631 function getMinorEdit() {
632 $this->loadLastEdit();
633 return $this->mMinorEdit;
634 }
635
636 function getRevIdFetched() {
637 $this->loadLastEdit();
638 return $this->mRevIdFetched;
639 }
640
641 function getContributors($limit = 0, $offset = 0) {
642 $fname = 'Article::getContributors';
643
644 # XXX: this is expensive; cache this info somewhere.
645
646 $title = $this->mTitle;
647 $contribs = array();
648 $dbr =& $this->getDB();
649 $revTable = $dbr->tableName( 'revision' );
650 $userTable = $dbr->tableName( 'user' );
651 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
652 $ns = $title->getNamespace();
653 $user = $this->getUser();
654 $pageId = $this->getId();
655
656 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
657 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
658 WHERE rev_page = $pageId
659 AND rev_user != $user
660 GROUP BY rev_user, rev_user_text, user_real_name
661 ORDER BY timestamp DESC";
662
663 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
664 $sql .= ' '. $this->getSelectOptions();
665
666 $res = $dbr->query($sql, $fname);
667
668 while ( $line = $dbr->fetchObject( $res ) ) {
669 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
670 }
671
672 $dbr->freeResult($res);
673 return $contribs;
674 }
675
676 /**
677 * This is the default action of the script: just view the page of
678 * the given title.
679 */
680 function view() {
681 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
682 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
683 global $wgEnotif, $wgParser, $wgParserCache, $wgUseTrackbacks;
684 $sk = $wgUser->getSkin();
685
686 $fname = 'Article::view';
687 wfProfileIn( $fname );
688 # Get variables from query string
689 $oldid = $this->getOldID();
690 $diff = $wgRequest->getVal( 'diff' );
691 $rcid = $wgRequest->getVal( 'rcid' );
692 $rdfrom = $wgRequest->getVal( 'rdfrom' );
693
694 $wgOut->setArticleFlag( true );
695 $wgOut->setRobotpolicy( 'index,follow' );
696 # If we got diff and oldid in the query, we want to see a
697 # diff page instead of the article.
698
699 if ( !is_null( $diff ) ) {
700 require_once( 'DifferenceEngine.php' );
701 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
702
703 $de = new DifferenceEngine( $oldid, $diff, $rcid );
704 // DifferenceEngine directly fetched the revision:
705 $this->mRevIdFetched = $de->mNewid;
706 $de->showDiffPage();
707
708 if( $diff == 0 ) {
709 # Run view updates for current revision only
710 $this->viewUpdates();
711 }
712 wfProfileOut( $fname );
713 return;
714 }
715
716 if ( empty( $oldid ) && $this->checkTouched() ) {
717 $wgOut->setETag($wgParserCache->getETag($this, $wgUser));
718
719 if( $wgOut->checkLastModified( $this->mTouched ) ){
720 wfProfileOut( $fname );
721 return;
722 } else if ( $this->tryFileCache() ) {
723 # tell wgOut that output is taken care of
724 $wgOut->disable();
725 $this->viewUpdates();
726 wfProfileOut( $fname );
727 return;
728 }
729 }
730 # Should the parser cache be used?
731 $pcache = $wgEnableParserCache &&
732 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
733 $this->exists() &&
734 empty( $oldid );
735 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
736
737 $outputDone = false;
738 if ( $pcache ) {
739 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
740 $outputDone = true;
741 }
742 }
743 if ( !$outputDone ) {
744 $text = $this->getContent( false ); # May change mTitle by following a redirect
745
746 # Another whitelist check in case oldid or redirects are altering the title
747 if ( !$this->mTitle->userCanRead() ) {
748 $wgOut->loginToUse();
749 $wgOut->output();
750 exit;
751 }
752
753 # We're looking at an old revision
754
755 if ( !empty( $oldid ) ) {
756 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
757 $wgOut->setRobotpolicy( 'noindex,follow' );
758 }
759 if ( '' != $this->mRedirectedFrom ) {
760 $sk = $wgUser->getSkin();
761 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
762 'redirect=no' );
763 $s = wfMsg( 'redirectedfrom', $redir );
764 $wgOut->setSubtitle( $s );
765
766 # Can't cache redirects
767 $pcache = false;
768 } elseif ( !empty( $rdfrom ) ) {
769 global $wgRedirectSources;
770 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
771 $sk = $wgUser->getSkin();
772 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
773 $s = wfMsg( 'redirectedfrom', $redir );
774 $wgOut->setSubtitle( $s );
775 }
776 }
777
778 # wrap user css and user js in pre and don't parse
779 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
780 if (
781 $this->mTitle->getNamespace() == NS_USER &&
782 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
783 ) {
784 $wgOut->addWikiText( wfMsg('clearyourcache'));
785 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
786 } else if ( $rt = Title::newFromRedirect( $text ) ) {
787 # Display redirect
788 $imageUrl = $wgStylePath.'/common/images/redirect.png';
789 $targetUrl = $rt->escapeLocalURL();
790 $titleText = htmlspecialchars( $rt->getPrefixedText() );
791 $link = $sk->makeLinkObj( $rt );
792
793 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
794 '<span class="redirectText">'.$link.'</span>' );
795
796 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
797 $catlinks = $parseout->getCategoryLinks();
798 $wgOut->addCategoryLinks($catlinks);
799 $skin = $wgUser->getSkin();
800 } else if ( $pcache ) {
801 # Display content and save to parser cache
802 $wgOut->addPrimaryWikiText( $text, $this );
803 } else {
804 # Display content, don't attempt to save to parser cache
805
806 # Don't show section-edit links on old revisions... this way lies madness.
807 if( !$this->isCurrent() ) {
808 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
809 }
810 $wgOut->addWikiText( $text );
811
812 if( !$this->isCurrent() ) {
813 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
814 }
815 }
816 }
817 /* title may have been set from the cache */
818 $t = $wgOut->getPageTitle();
819 if( empty( $t ) ) {
820 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
821 }
822
823 # If we have been passed an &rcid= parameter, we want to give the user a
824 # chance to mark this new article as patrolled.
825 if ( $wgUseRCPatrol
826 && !is_null($rcid)
827 && $rcid != 0
828 && $wgUser->isLoggedIn()
829 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
830 {
831 $wgOut->addHTML(
832 "<div class='patrollink'>" .
833 wfMsg ( 'markaspatrolledlink',
834 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
835 ) .
836 '</div>'
837 );
838 }
839
840 # Trackbacks
841 if ($wgUseTrackbacks)
842 $this->addTrackbacks();
843
844 # Put link titles into the link cache
845 $wgOut->transformBuffer();
846
847 # Add link titles as META keywords
848 $wgOut->addMetaTags() ;
849
850 $this->viewUpdates();
851 wfProfileOut( $fname );
852 }
853
854 function addTrackbacks() {
855 global $wgOut, $wgUser;
856
857 $dbr =& wfGetDB(DB_SLAVE);
858 $tbs = $dbr->select(
859 /* FROM */ 'trackbacks',
860 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
861 /* WHERE */ array('tb_page' => $this->getID())
862 );
863
864 if (!$dbr->numrows($tbs))
865 return;
866
867 $tbtext = "";
868 while ($o = $dbr->fetchObject($tbs)) {
869 $rmvtxt = "";
870 if ($wgUser->isSysop()) {
871 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
872 . $o->tb_id . "&token=" . $wgUser->editToken());
873 $rmvtxt = wfMsg('trackbackremove', $delurl);
874 }
875 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
876 $o->tb_title,
877 $o->tb_url,
878 $o->tb_ex,
879 $o->tb_name,
880 $rmvtxt);
881 }
882 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
883 }
884
885 function deletetrackback() {
886 global $wgUser, $wgRequest, $wgOut, $wgTitle;
887
888 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
889 $wgOut->addWikitext(wfMsg('sessionfailure'));
890 return;
891 }
892
893 if ((!$wgUser->isAllowed('delete'))) {
894 $wgOut->sysopRequired();
895 return;
896 }
897
898 if (wfReadOnly()) {
899 $wgOut->readOnlyPage();
900 return;
901 }
902
903 $db =& wfGetDB(DB_MASTER);
904 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
905 $wgTitle->invalidateCache();
906 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
907 }
908
909 function render() {
910 global $wgOut;
911
912 $wgOut->setArticleBodyOnly(true);
913 $this->view();
914 }
915
916 /**
917 * Insert a new empty page record for this article.
918 * This *must* be followed up by creating a revision
919 * and running $this->updateToLatest( $rev_id );
920 * or else the record will be left in a funky state.
921 * Best if all done inside a transaction.
922 *
923 * @param Database $dbw
924 * @param string $restrictions
925 * @return int The newly created page_id key
926 * @access private
927 */
928 function insertOn( &$dbw, $restrictions = '' ) {
929 $fname = 'Article::insertOn';
930 wfProfileIn( $fname );
931
932 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
933 $dbw->insert( 'page', array(
934 'page_id' => $page_id,
935 'page_namespace' => $this->mTitle->getNamespace(),
936 'page_title' => $this->mTitle->getDBkey(),
937 'page_counter' => 0,
938 'page_restrictions' => $restrictions,
939 'page_is_redirect' => 0, # Will set this shortly...
940 'page_is_new' => 1,
941 'page_random' => wfRandom(),
942 'page_touched' => $dbw->timestamp(),
943 'page_latest' => 0, # Fill this in shortly...
944 ), $fname );
945 $newid = $dbw->insertId();
946
947 $this->mTitle->resetArticleId( $newid );
948
949 wfProfileOut( $fname );
950 return $newid;
951 }
952
953 /**
954 * Update the page record to point to a newly saved revision.
955 *
956 * @param Database $dbw
957 * @param Revision $revision -- for ID number, and text used to set
958 length and redirect status fields
959 * @param int $lastRevision -- if given, will not overwrite the page field
960 * when different from the currently set value.
961 * Giving 0 indicates the new page flag should
962 * be set on.
963 * @return bool true on success, false on failure
964 * @access private
965 */
966 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
967 $fname = 'Article::updateToRevision';
968 wfProfileIn( $fname );
969
970 $conditions = array( 'page_id' => $this->getId() );
971 if( !is_null( $lastRevision ) ) {
972 # An extra check against threads stepping on each other
973 $conditions['page_latest'] = $lastRevision;
974 }
975
976 $text = $revision->getText();
977 $dbw->update( 'page',
978 array( /* SET */
979 'page_latest' => $revision->getId(),
980 'page_touched' => $dbw->timestamp(),
981 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
982 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
983 'page_len' => strlen( $text ),
984 ),
985 $conditions,
986 $fname );
987
988 wfProfileOut( $fname );
989 return ( $dbw->affectedRows() != 0 );
990 }
991
992 /**
993 * If the given revision is newer than the currently set page_latest,
994 * update the page record. Otherwise, do nothing.
995 *
996 * @param Database $dbw
997 * @param Revision $revision
998 */
999 function updateIfNewerOn( &$dbw, $revision ) {
1000 $fname = 'Article::updateIfNewerOn';
1001 wfProfileIn( $fname );
1002
1003 $row = $dbw->selectRow(
1004 array( 'revision', 'page' ),
1005 array( 'rev_id', 'rev_timestamp' ),
1006 array(
1007 'page_id' => $this->getId(),
1008 'page_latest=rev_id' ),
1009 $fname );
1010 if( $row ) {
1011 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1012 wfProfileOut( $fname );
1013 return false;
1014 }
1015 $prev = $row->rev_id;
1016 } else {
1017 # No or missing previous revision; mark the page as new
1018 $prev = 0;
1019 }
1020
1021 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1022 wfProfileOut( $fname );
1023 return $ret;
1024 }
1025
1026 /**
1027 * Theoretically we could defer these whole insert and update
1028 * functions for after display, but that's taking a big leap
1029 * of faith, and we want to be able to report database
1030 * errors at some point.
1031 * @private
1032 */
1033 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1034 global $wgOut, $wgUser;
1035 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1036
1037 $fname = 'Article::insertNewArticle';
1038 wfProfileIn( $fname );
1039
1040 $this->mGoodAdjustment = $this->isCountable( $text );
1041 $this->mTotalAdjustment = 1;
1042
1043 $ns = $this->mTitle->getNamespace();
1044 $ttl = $this->mTitle->getDBkey();
1045
1046 # If this is a comment, add the summary as headline
1047 if($comment && $summary!="") {
1048 $text="== {$summary} ==\n\n".$text;
1049 }
1050 $text = $this->preSaveTransform( $text );
1051 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
1052 $now = wfTimestampNow();
1053
1054 $dbw =& wfGetDB( DB_MASTER );
1055
1056 # Add the page record; stake our claim on this title!
1057 $newid = $this->insertOn( $dbw );
1058
1059 # Save the revision text...
1060 $revision = new Revision( array(
1061 'page' => $newid,
1062 'comment' => $summary,
1063 'minor_edit' => $isminor,
1064 'text' => $text
1065 ) );
1066 $revisionId = $revision->insertOn( $dbw );
1067
1068 $this->mTitle->resetArticleID( $newid );
1069
1070 # Update the page record with revision data
1071 $this->updateRevisionOn( $dbw, $revision, 0 );
1072
1073 Article::onArticleCreate( $this->mTitle );
1074 if(!$suppressRC) {
1075 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1076 '', strlen( $text ), $revisionId );
1077 }
1078
1079 if ($watchthis) {
1080 if(!$this->mTitle->userIsWatching()) $this->watch();
1081 } else {
1082 if ( $this->mTitle->userIsWatching() ) {
1083 $this->unwatch();
1084 }
1085 }
1086
1087 # The talk page isn't in the regular link tables, so we need to update manually:
1088 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1089 $dbw->update( 'page',
1090 array( 'page_touched' => $dbw->timestamp($now) ),
1091 array( 'page_namespace' => $talkns,
1092 'page_title' => $ttl ),
1093 $fname );
1094
1095 # standard deferred updates
1096 $this->editUpdates( $text, $summary, $isminor, $now );
1097
1098 $oldid = 0; # new article
1099 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1100 wfProfileOut( $fname );
1101 }
1102
1103 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1104 $this->replaceSection( $section, $text, $summary, $edittime );
1105 }
1106
1107 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1108 $fname = 'Article::replaceSection';
1109 wfProfileIn( $fname );
1110
1111 if ($section != '') {
1112 if( is_null( $edittime ) ) {
1113 $rev = Revision::newFromTitle( $this->mTitle );
1114 } else {
1115 $dbw =& wfGetDB( DB_MASTER );
1116 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1117 }
1118 $oldtext = $rev->getText();
1119
1120 if($section=='new') {
1121 if($summary) $subject="== {$summary} ==\n\n";
1122 $text=$oldtext."\n\n".$subject.$text;
1123 } else {
1124
1125 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1126 # comments to be stripped as well)
1127 $striparray=array();
1128 $parser=new Parser();
1129 $parser->mOutputType=OT_WIKI;
1130 $oldtext=$parser->strip($oldtext, $striparray, true);
1131
1132 # now that we can be sure that no pseudo-sections are in the source,
1133 # split it up
1134 # Unfortunately we can't simply do a preg_replace because that might
1135 # replace the wrong section, so we have to use the section counter instead
1136 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1137 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1138 $secs[$section*2]=$text."\n\n"; // replace with edited
1139
1140 # section 0 is top (intro) section
1141 if($section!=0) {
1142
1143 # headline of old section - we need to go through this section
1144 # to determine if there are any subsections that now need to
1145 # be erased, as the mother section has been replaced with
1146 # the text of all subsections.
1147 $headline=$secs[$section*2-1];
1148 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1149 $hlevel=$matches[1];
1150
1151 # determine headline level for wikimarkup headings
1152 if(strpos($hlevel,'=')!==false) {
1153 $hlevel=strlen($hlevel);
1154 }
1155
1156 $secs[$section*2-1]=''; // erase old headline
1157 $count=$section+1;
1158 $break=false;
1159 while(!empty($secs[$count*2-1]) && !$break) {
1160
1161 $subheadline=$secs[$count*2-1];
1162 preg_match(
1163 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1164 $subhlevel=$matches[1];
1165 if(strpos($subhlevel,'=')!==false) {
1166 $subhlevel=strlen($subhlevel);
1167 }
1168 if($subhlevel > $hlevel) {
1169 // erase old subsections
1170 $secs[$count*2-1]='';
1171 $secs[$count*2]='';
1172 }
1173 if($subhlevel <= $hlevel) {
1174 $break=true;
1175 }
1176 $count++;
1177
1178 }
1179
1180 }
1181 $text=join('',$secs);
1182 # reinsert the stuff that we stripped out earlier
1183 $text=$parser->unstrip($text,$striparray);
1184 $text=$parser->unstripNoWiki($text,$striparray);
1185 }
1186
1187 }
1188 wfProfileOut( $fname );
1189 return $text;
1190 }
1191
1192 /**
1193 * Change an existing article. Puts the previous version back into the old table, updates RC
1194 * and all necessary caches, mostly via the deferred update array.
1195 *
1196 * It is possible to call this function from a command-line script, but note that you should
1197 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1198 */
1199 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1200 global $wgOut, $wgUser;
1201 global $wgDBtransactions, $wgMwRedir;
1202 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList, $wgUseFileCache;
1203
1204 $fname = 'Article::updateArticle';
1205 wfProfileIn( $fname );
1206 $good = true;
1207
1208 $isminor = ( $minor && $wgUser->isLoggedIn() );
1209 if ( $this->isRedirect( $text ) ) {
1210 # Remove all content but redirect
1211 # This could be done by reconstructing the redirect from a title given by
1212 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1213 # wants to see
1214 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1215 $redir = 1;
1216 $text = $m[1] . "\n";
1217 }
1218 }
1219 else { $redir = 0; }
1220
1221 $text = $this->preSaveTransform( $text );
1222 $dbw =& wfGetDB( DB_MASTER );
1223 $now = wfTimestampNow();
1224
1225 # Update article, but only if changed.
1226
1227 # It's important that we either rollback or complete, otherwise an attacker could
1228 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1229 # could conceivably have the same effect, especially if cur is locked for long periods.
1230 if( !$wgDBtransactions ) {
1231 $userAbort = ignore_user_abort( true );
1232 }
1233
1234 $oldtext = $this->getContent( true );
1235 $oldsize = strlen( $oldtext );
1236 $newsize = strlen( $text );
1237 $lastRevision = 0;
1238
1239 if ( 0 != strcmp( $text, $oldtext ) ) {
1240 $this->mGoodAdjustment = $this->isCountable( $text )
1241 - $this->isCountable( $oldtext );
1242 $this->mTotalAdjustment = 0;
1243 $now = wfTimestampNow();
1244
1245 $lastRevision = $dbw->selectField(
1246 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1247
1248 $revision = new Revision( array(
1249 'page' => $this->getId(),
1250 'comment' => $summary,
1251 'minor_edit' => $isminor,
1252 'text' => $text
1253 ) );
1254
1255 $dbw->immediateCommit();
1256 $dbw->begin();
1257 $revisionId = $revision->insertOn( $dbw );
1258
1259 # Update page
1260 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1261
1262 if( !$ok ) {
1263 /* Belated edit conflict! Run away!! */
1264 $good = false;
1265 $dbw->rollback();
1266 } else {
1267 # Update recentchanges and purge cache and whatnot
1268 $bot = (int)($wgUser->isBot() || $forceBot);
1269 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1270 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1271 $revisionId );
1272 Article::onArticleEdit( $this->mTitle );
1273 $dbw->commit();
1274 }
1275 }
1276
1277 if( !$wgDBtransactions ) {
1278 ignore_user_abort( $userAbort );
1279 }
1280
1281 if ( $good ) {
1282 if ($watchthis) {
1283 if (!$this->mTitle->userIsWatching()) {
1284 $dbw->immediateCommit();
1285 $dbw->begin();
1286 $this->watch();
1287 $dbw->commit();
1288 }
1289 } else {
1290 if ( $this->mTitle->userIsWatching() ) {
1291 $dbw->immediateCommit();
1292 $dbw->begin();
1293 $this->unwatch();
1294 $dbw->commit();
1295 }
1296 }
1297 # standard deferred updates
1298 $this->editUpdates( $text, $summary, $minor, $now );
1299
1300
1301 $urls = array();
1302 # Template namespace
1303 # Purge all articles linking here
1304 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1305 $titles = $this->mTitle->getLinksTo();
1306 Title::touchArray( $titles );
1307 if ( $wgUseSquid ) {
1308 foreach ( $titles as $title ) {
1309 $urls[] = $title->getInternalURL();
1310 }
1311 }
1312 }
1313
1314 # Squid updates
1315 if ( $wgUseSquid ) {
1316 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1317 $u = new SquidUpdate( $urls );
1318 array_push( $wgPostCommitUpdateList, $u );
1319 }
1320
1321 # File cache
1322 if ( $wgUseFileCache ) {
1323 $cm = new CacheManager($this->mTitle);
1324 @unlink($cm->fileCacheName());
1325 }
1326
1327 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1328 }
1329 wfProfileOut( $fname );
1330 return $good;
1331 }
1332
1333 /**
1334 * After we've either updated or inserted the article, update
1335 * the link tables and redirect to the new page.
1336 */
1337 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1338 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1339 global $wgUseEnotif;
1340
1341 $fname = 'Article::showArticle';
1342 wfProfileIn( $fname );
1343
1344 $wgLinkCache = new LinkCache();
1345
1346 if ( !$wgUseDumbLinkUpdate ) {
1347 # Preload links to reduce lock time
1348 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS ) {
1349 $wgLinkCache->preFill( $this->mTitle );
1350 $wgLinkCache->clear();
1351 }
1352 }
1353
1354 # Parse the text and replace links with placeholders
1355 $wgOut = new OutputPage();
1356
1357 # Pass the current title along in case we're creating a wiki page
1358 # which is different than the currently displayed one (e.g. image
1359 # pages created on file uploads); otherwise, link updates will
1360 # go wrong.
1361 $wgOut->addWikiTextWithTitle( $text, $this->mTitle );
1362
1363 if ( !$wgUseDumbLinkUpdate ) {
1364 # Move the current links back to the second register
1365 $wgLinkCache->swapRegisters();
1366
1367 # Get old version of link table to allow incremental link updates
1368 # Lock this data now since it is needed for an update
1369 $wgLinkCache->forUpdate( true );
1370 $wgLinkCache->preFill( $this->mTitle );
1371
1372 # Swap this old version back into its rightful place
1373 $wgLinkCache->swapRegisters();
1374 }
1375
1376 if( $this->isRedirect( $text ) )
1377 $r = 'redirect=no';
1378 else
1379 $r = '';
1380 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1381
1382 if ( $wgUseEnotif ) {
1383 # this would be better as an extension hook
1384 include_once( "UserMailer.php" );
1385 $wgEnotif = new EmailNotification ();
1386 $wgEnotif->notifyOnPageChange( $this->mTitle, $now, $summary, $me2, $oldid );
1387 }
1388 wfProfileOut( $fname );
1389 }
1390
1391 /**
1392 * Mark this particular edit as patrolled
1393 */
1394 function markpatrolled() {
1395 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1396 $wgOut->setRobotpolicy( 'noindex,follow' );
1397
1398 if ( !$wgUseRCPatrol )
1399 {
1400 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1401 return;
1402 }
1403 if ( $wgUser->isAnon() )
1404 {
1405 $wgOut->loginToUse();
1406 return;
1407 }
1408 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1409 {
1410 $wgOut->sysopRequired();
1411 return;
1412 }
1413 $rcid = $wgRequest->getVal( 'rcid' );
1414 if ( !is_null ( $rcid ) )
1415 {
1416 RecentChange::markPatrolled( $rcid );
1417 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1418 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1419
1420 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1421 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1422 }
1423 else
1424 {
1425 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1426 }
1427 }
1428
1429 /**
1430 * Validate function
1431 */
1432 function validate() {
1433 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1434
1435 if ( !$wgUseValidation ) # Are we using article validation at all?
1436 {
1437 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1438 return ;
1439 }
1440
1441 $wgOut->setRobotpolicy( 'noindex,follow' );
1442 $revision = $wgRequest->getVal( 'revision' );
1443
1444 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1445
1446 $v = new Validation ;
1447 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1448 $t = $v->showList ( $this ) ;
1449 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1450 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1451 else
1452 $t = $v->validatePageForm ( $this , $revision ) ;
1453
1454 $wgOut->addHTML ( $t ) ;
1455 }
1456
1457 /**
1458 * Add this page to $wgUser's watchlist
1459 */
1460
1461 function watch() {
1462
1463 global $wgUser, $wgOut;
1464
1465 if ( $wgUser->isAnon() ) {
1466 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1467 return;
1468 }
1469 if ( wfReadOnly() ) {
1470 $wgOut->readOnlyPage();
1471 return;
1472 }
1473
1474 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1475
1476 $wgUser->addWatch( $this->mTitle );
1477 $wgUser->saveSettings();
1478
1479 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1480
1481 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1482 $wgOut->setRobotpolicy( 'noindex,follow' );
1483
1484 $link = $this->mTitle->getPrefixedText();
1485 $text = wfMsg( 'addedwatchtext', $link );
1486 $wgOut->addWikiText( $text );
1487 }
1488
1489 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1490 }
1491
1492 /**
1493 * Stop watching a page
1494 */
1495
1496 function unwatch() {
1497
1498 global $wgUser, $wgOut;
1499
1500 if ( $wgUser->isAnon() ) {
1501 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1502 return;
1503 }
1504 if ( wfReadOnly() ) {
1505 $wgOut->readOnlyPage();
1506 return;
1507 }
1508
1509 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1510
1511 $wgUser->removeWatch( $this->mTitle );
1512 $wgUser->saveSettings();
1513
1514 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1515
1516 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1517 $wgOut->setRobotpolicy( 'noindex,follow' );
1518
1519 $link = $this->mTitle->getPrefixedText();
1520 $text = wfMsg( 'removedwatchtext', $link );
1521 $wgOut->addWikiText( $text );
1522 }
1523
1524 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1525 }
1526
1527 /**
1528 * protect a page
1529 */
1530 function protect( $limit = 'sysop' ) {
1531 global $wgUser, $wgOut, $wgRequest;
1532
1533 if ( ! $wgUser->isAllowed('protect') ) {
1534 $wgOut->sysopRequired();
1535 return;
1536 }
1537 if ( wfReadOnly() ) {
1538 $wgOut->readOnlyPage();
1539 return;
1540 }
1541 $id = $this->mTitle->getArticleID();
1542 if ( 0 == $id ) {
1543 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1544 return;
1545 }
1546
1547 $confirm = $wgRequest->wasPosted() &&
1548 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1549 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1550 $reason = $wgRequest->getText( 'wpReasonProtect' );
1551
1552 if ( $confirm ) {
1553 $dbw =& wfGetDB( DB_MASTER );
1554 $dbw->update( 'page',
1555 array( /* SET */
1556 'page_touched' => $dbw->timestamp(),
1557 'page_restrictions' => (string)$limit
1558 ), array( /* WHERE */
1559 'page_id' => $id
1560 ), 'Article::protect'
1561 );
1562
1563 $restrictions = "move=" . $limit;
1564 if( !$moveonly ) {
1565 $restrictions .= ":edit=" . $limit;
1566 }
1567 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1568
1569 $dbw =& wfGetDB( DB_MASTER );
1570 $dbw->update( 'page',
1571 array( /* SET */
1572 'page_touched' => $dbw->timestamp(),
1573 'page_restrictions' => $restrictions
1574 ), array( /* WHERE */
1575 'page_id' => $id
1576 ), 'Article::protect'
1577 );
1578
1579 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1580
1581 $log = new LogPage( 'protect' );
1582 if ( $limit === '' ) {
1583 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1584 } else {
1585 $log->addEntry( 'protect', $this->mTitle, $reason );
1586 }
1587 $wgOut->redirect( $this->mTitle->getFullURL() );
1588 }
1589 return;
1590 } else {
1591 return $this->confirmProtect( '', '', $limit );
1592 }
1593 }
1594
1595 /**
1596 * Output protection confirmation dialog
1597 */
1598 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1599 global $wgOut, $wgUser;
1600
1601 wfDebug( "Article::confirmProtect\n" );
1602
1603 $sub = $this->mTitle->getPrefixedText();
1604 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1605
1606 $check = '';
1607 $protcom = '';
1608 $moveonly = '';
1609
1610 if ( $limit === '' ) {
1611 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1612 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1613 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1614 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1615 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1616 } else {
1617 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1618 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1619 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1620 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1621 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1622 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1623 }
1624
1625 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1626 $token = htmlspecialchars( $wgUser->editToken() );
1627
1628 $wgOut->addHTML( "
1629 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1630 <table border='0'>
1631 <tr>
1632 <td align='right'>
1633 <label for='wpReasonProtect'>{$protcom}:</label>
1634 </td>
1635 <td align='left'>
1636 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1637 </td>
1638 </tr>" );
1639 if($moveonly != '') {
1640 $wgOut->AddHTML( "
1641 <tr>
1642 <td align='right'>
1643 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1644 </td>
1645 <td align='left'>
1646 <label for='wpMoveOnly'>{$moveonly}</label>
1647 </td>
1648 </tr> " );
1649 }
1650 $wgOut->addHTML( "
1651 <tr>
1652 <td>&nbsp;</td>
1653 <td>
1654 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1655 </td>
1656 </tr>
1657 </table>
1658 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1659 </form>" );
1660
1661 $wgOut->returnToMain( false );
1662 }
1663
1664 /**
1665 * Unprotect the pages
1666 */
1667 function unprotect() {
1668 return $this->protect( '' );
1669 }
1670
1671 /*
1672 * UI entry point for page deletion
1673 */
1674 function delete() {
1675 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1676 $fname = 'Article::delete';
1677 $confirm = $wgRequest->wasPosted() &&
1678 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1679 $reason = $wgRequest->getText( 'wpReason' );
1680
1681 # This code desperately needs to be totally rewritten
1682
1683 # Check permissions
1684 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1685 $wgOut->sysopRequired();
1686 return;
1687 }
1688 if( wfReadOnly() ) {
1689 $wgOut->readOnlyPage();
1690 return;
1691 }
1692
1693 # Better double-check that it hasn't been deleted yet!
1694 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1695 if( !$this->mTitle->exists() ) {
1696 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1697 return;
1698 }
1699
1700 if( $confirm ) {
1701 $this->doDelete( $reason );
1702 return;
1703 }
1704
1705 # determine whether this page has earlier revisions
1706 # and insert a warning if it does
1707 # we select the text because it might be useful below
1708 $dbr =& $this->getDB();
1709 $ns = $this->mTitle->getNamespace();
1710 $title = $this->mTitle->getDBkey();
1711 $revisions = $dbr->select( array( 'page', 'revision' ),
1712 array( 'rev_id', 'rev_user_text' ),
1713 array(
1714 'page_namespace' => $ns,
1715 'page_title' => $title,
1716 'rev_page = page_id'
1717 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1718 );
1719
1720 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1721 $skin=$wgUser->getSkin();
1722 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1723 $wgOut->addHTML( $skin->historyLink() .'</b>');
1724 }
1725
1726 # Fetch cur_text
1727 $rev = Revision::newFromTitle( $this->mTitle );
1728
1729 # Fetch name(s) of contributors
1730 $rev_name = '';
1731 $all_same_user = true;
1732 while( $row = $dbr->fetchObject( $revisions ) ) {
1733 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1734 $all_same_user = false;
1735 } else {
1736 $rev_name = $row->rev_user_text;
1737 }
1738 }
1739
1740 if( !is_null( $rev ) ) {
1741 # if this is a mini-text, we can paste part of it into the deletion reason
1742 $text = $rev->getText();
1743
1744 #if this is empty, an earlier revision may contain "useful" text
1745 $blanked = false;
1746 if( $text == '' ) {
1747 $prev = $rev->getPrevious();
1748 if( $prev ) {
1749 $text = $prev->getText();
1750 $blanked = true;
1751 }
1752 }
1753
1754 $length = strlen( $text );
1755
1756 # this should not happen, since it is not possible to store an empty, new
1757 # page. Let's insert a standard text in case it does, though
1758 if( $length == 0 && $reason === '' ) {
1759 $reason = wfMsgForContent( 'exblank' );
1760 }
1761
1762 if( $length < 500 && $reason === '' ) {
1763 # comment field=255, let's grep the first 150 to have some user
1764 # space left
1765 global $wgContLang;
1766 $text = $wgContLang->truncate( $text, 150, '...' );
1767
1768 # let's strip out newlines
1769 $text = preg_replace( "/[\n\r]/", '', $text );
1770
1771 if( !$blanked ) {
1772 if( !$all_same_user ) {
1773 $reason = wfMsgForContent( 'excontent', $text );
1774 } else {
1775 $reason = wfMsgForContent( 'excontentauthor', $text, $rev_name );
1776 }
1777 } else {
1778 $reason = wfMsgForContent( 'exbeforeblank', $text );
1779 }
1780 }
1781 }
1782
1783 return $this->confirmDelete( '', $reason );
1784 }
1785
1786 /**
1787 * Output deletion confirmation dialog
1788 */
1789 function confirmDelete( $par, $reason ) {
1790 global $wgOut, $wgUser;
1791
1792 wfDebug( "Article::confirmDelete\n" );
1793
1794 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1795 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1796 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1797 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1798
1799 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1800
1801 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1802 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1803 $token = htmlspecialchars( $wgUser->editToken() );
1804
1805 $wgOut->addHTML( "
1806 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1807 <table border='0'>
1808 <tr>
1809 <td align='right'>
1810 <label for='wpReason'>{$delcom}:</label>
1811 </td>
1812 <td align='left'>
1813 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1814 </td>
1815 </tr>
1816 <tr>
1817 <td>&nbsp;</td>
1818 <td>
1819 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1820 </td>
1821 </tr>
1822 </table>
1823 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1824 </form>\n" );
1825
1826 $wgOut->returnToMain( false );
1827 }
1828
1829
1830 /**
1831 * Perform a deletion and output success or failure messages
1832 */
1833 function doDelete( $reason ) {
1834 global $wgOut, $wgUser, $wgContLang;
1835 $fname = 'Article::doDelete';
1836 wfDebug( $fname."\n" );
1837
1838 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1839 if ( $this->doDeleteArticle( $reason ) ) {
1840 $deleted = $this->mTitle->getPrefixedText();
1841
1842 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1843 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1844
1845 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1846 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1847
1848 $wgOut->addWikiText( $text );
1849 $wgOut->returnToMain( false );
1850 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1851 } else {
1852 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1853 }
1854 }
1855 }
1856
1857 /**
1858 * Back-end article deletion
1859 * Deletes the article with database consistency, writes logs, purges caches
1860 * Returns success
1861 */
1862 function doDeleteArticle( $reason ) {
1863 global $wgUser;
1864 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1865 global $wgUseTrackbacks;
1866
1867 $fname = 'Article::doDeleteArticle';
1868 wfDebug( $fname."\n" );
1869
1870 $dbw =& wfGetDB( DB_MASTER );
1871 $ns = $this->mTitle->getNamespace();
1872 $t = $this->mTitle->getDBkey();
1873 $id = $this->mTitle->getArticleID();
1874
1875 if ( $t == '' || $id == 0 ) {
1876 return false;
1877 }
1878
1879 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1880 array_push( $wgDeferredUpdateList, $u );
1881
1882 $linksTo = $this->mTitle->getLinksTo();
1883
1884 # Squid purging
1885 if ( $wgUseSquid ) {
1886 $urls = array(
1887 $this->mTitle->getInternalURL(),
1888 $this->mTitle->getInternalURL( 'history' )
1889 );
1890
1891 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1892 array_push( $wgPostCommitUpdateList, $u );
1893
1894 }
1895
1896 # Client and file cache invalidation
1897 Title::touchArray( $linksTo );
1898
1899
1900 // For now, shunt the revision data into the archive table.
1901 // Text is *not* removed from the text table; bulk storage
1902 // is left intact to avoid breaking block-compression or
1903 // immutable storage schemes.
1904 //
1905 // For backwards compatibility, note that some older archive
1906 // table entries will have ar_text and ar_flags fields still.
1907 //
1908 // In the future, we may keep revisions and mark them with
1909 // the rev_deleted field, which is reserved for this purpose.
1910 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1911 array(
1912 'ar_namespace' => 'page_namespace',
1913 'ar_title' => 'page_title',
1914 'ar_comment' => 'rev_comment',
1915 'ar_user' => 'rev_user',
1916 'ar_user_text' => 'rev_user_text',
1917 'ar_timestamp' => 'rev_timestamp',
1918 'ar_minor_edit' => 'rev_minor_edit',
1919 'ar_rev_id' => 'rev_id',
1920 'ar_text_id' => 'rev_text_id',
1921 ), array(
1922 'page_id' => $id,
1923 'page_id = rev_page'
1924 ), $fname
1925 );
1926
1927 # Now that it's safely backed up, delete it
1928 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1929 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1930
1931 if ($wgUseTrackbacks)
1932 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
1933
1934 # Clean up recentchanges entries...
1935 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1936
1937 # Finally, clean up the link tables
1938 $t = $this->mTitle->getPrefixedDBkey();
1939
1940 Article::onArticleDelete( $this->mTitle );
1941
1942 # Delete outgoing links
1943 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1944 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1945 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1946
1947 # Log the deletion
1948 $log = new LogPage( 'delete' );
1949 $log->addEntry( 'delete', $this->mTitle, $reason );
1950
1951 # Clear the cached article id so the interface doesn't act like we exist
1952 $this->mTitle->resetArticleID( 0 );
1953 $this->mTitle->mArticleID = 0;
1954 return true;
1955 }
1956
1957 /**
1958 * Revert a modification
1959 */
1960 function rollback() {
1961 global $wgUser, $wgOut, $wgRequest;
1962 $fname = 'Article::rollback';
1963
1964 if ( ! $wgUser->isAllowed('rollback') ) {
1965 $wgOut->sysopRequired();
1966 return;
1967 }
1968 if ( wfReadOnly() ) {
1969 $wgOut->readOnlyPage( $this->getContent( true ) );
1970 return;
1971 }
1972 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1973 array( $this->mTitle->getPrefixedText(),
1974 $wgRequest->getVal( 'from' ) ) ) ) {
1975 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1976 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1977 return;
1978 }
1979 $dbw =& wfGetDB( DB_MASTER );
1980
1981 # Enhanced rollback, marks edits rc_bot=1
1982 $bot = $wgRequest->getBool( 'bot' );
1983
1984 # Replace all this user's current edits with the next one down
1985 $tt = $this->mTitle->getDBKey();
1986 $n = $this->mTitle->getNamespace();
1987
1988 # Get the last editor, lock table exclusively
1989 $dbw->begin();
1990 $current = Revision::newFromTitle( $this->mTitle );
1991 if( is_null( $current ) ) {
1992 # Something wrong... no page?
1993 $dbw->rollback();
1994 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1995 return;
1996 }
1997
1998 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1999 if( $from != $current->getUserText() ) {
2000 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2001 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2002 htmlspecialchars( $this->mTitle->getPrefixedText()),
2003 htmlspecialchars( $from ),
2004 htmlspecialchars( $current->getUserText() ) ) );
2005 if( $current->getComment() != '') {
2006 $wgOut->addHTML(
2007 wfMsg( 'editcomment',
2008 htmlspecialchars( $current->getComment() ) ) );
2009 }
2010 return;
2011 }
2012
2013 # Get the last edit not by this guy
2014 $user = intval( $current->getUser() );
2015 $user_text = $dbw->addQuotes( $current->getUserText() );
2016 $s = $dbw->selectRow( 'revision',
2017 array( 'rev_id', 'rev_timestamp' ),
2018 array(
2019 'rev_page' => $current->getPage(),
2020 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2021 ), $fname,
2022 array(
2023 'USE INDEX' => 'page_timestamp',
2024 'ORDER BY' => 'rev_timestamp DESC' )
2025 );
2026 if( $s === false ) {
2027 # Something wrong
2028 $dbw->rollback();
2029 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2030 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2031 return;
2032 }
2033
2034 if ( $bot ) {
2035 # Mark all reverted edits as bot
2036 $dbw->update( 'recentchanges',
2037 array( /* SET */
2038 'rc_bot' => 1
2039 ), array( /* WHERE */
2040 'rc_cur_id' => $current->getPage(),
2041 'rc_user_text' => $current->getUserText(),
2042 "rc_timestamp > '{$s->rev_timestamp}'",
2043 ), $fname
2044 );
2045 }
2046
2047 # Save it!
2048 $target = Revision::newFromId( $s->rev_id );
2049 $newcomment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2050
2051 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2052 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2053 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
2054
2055 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
2056 Article::onArticleEdit( $this->mTitle );
2057
2058 $dbw->commit();
2059 $wgOut->returnToMain( false );
2060 }
2061
2062
2063 /**
2064 * Do standard deferred updates after page view
2065 * @private
2066 */
2067 function viewUpdates() {
2068 global $wgDeferredUpdateList, $wgUseEnotif;
2069
2070 if ( 0 != $this->getID() ) {
2071 global $wgDisableCounters;
2072 if( !$wgDisableCounters ) {
2073 Article::incViewCount( $this->getID() );
2074 $u = new SiteStatsUpdate( 1, 0, 0 );
2075 array_push( $wgDeferredUpdateList, $u );
2076 }
2077 }
2078
2079 # Update newtalk status if user is reading their own
2080 # talk page
2081
2082 global $wgUser;
2083 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
2084 $this->mTitle->getText() == $wgUser->getName())
2085 {
2086 if ( $wgUseEnotif ) {
2087 require_once( 'UserTalkUpdate.php' );
2088 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
2089 } else {
2090 $wgUser->setNewtalk(0);
2091 $wgUser->saveNewtalk();
2092 }
2093 } elseif ( $wgUseEnotif ) {
2094 $wgUser->clearNotification( $this->mTitle );
2095 }
2096
2097 }
2098
2099 /**
2100 * Do standard deferred updates after page edit.
2101 * Every 1000th edit, prune the recent changes table.
2102 * @private
2103 * @param string $text
2104 */
2105 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
2106 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
2107 global $wgMessageCache, $wgUser, $wgUseEnotif;
2108
2109 wfSeedRandom();
2110 if ( 0 == mt_rand( 0, 999 ) ) {
2111 # Periodically flush old entries from the recentchanges table.
2112 global $wgRCMaxAge;
2113 $dbw =& wfGetDB( DB_MASTER );
2114 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2115 $recentchanges = $dbw->tableName( 'recentchanges' );
2116 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2117 //$dbw->query( $sql ); // HACK: disabled for now, slowness
2118
2119 // re-enabled for commit of unrelated live changes -- TS
2120 $dbw->query( $sql );
2121 }
2122 $id = $this->getID();
2123 $title = $this->mTitle->getPrefixedDBkey();
2124 $shortTitle = $this->mTitle->getDBkey();
2125
2126 if ( 0 != $id ) {
2127 $u = new LinksUpdate( $id, $title );
2128 array_push( $wgDeferredUpdateList, $u );
2129 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2130 array_push( $wgDeferredUpdateList, $u );
2131 $u = new SearchUpdate( $id, $title, $text );
2132 array_push( $wgDeferredUpdateList, $u );
2133
2134 # If this is another user's talk page, update newtalk
2135
2136 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2137 if ( $wgUseEnotif ) {
2138 require_once( 'UserTalkUpdate.php' );
2139 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary,
2140 $minoredit, $timestamp_of_pagechange);
2141 } else {
2142 $other = User::newFromName( $shortTitle );
2143 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2144 // An anonymous user
2145 $other = new User();
2146 $other->setName( $shortTitle );
2147 }
2148 if( $other ) {
2149 $other->setNewtalk(1);
2150 $other->saveNewtalk();
2151 }
2152 }
2153 }
2154
2155 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2156 $wgMessageCache->replace( $shortTitle, $text );
2157 }
2158 }
2159 }
2160
2161 /**
2162 * @todo document this function
2163 * @private
2164 * @param string $oldid Revision ID of this article revision
2165 */
2166 function setOldSubtitle( $oldid=0 ) {
2167 global $wgLang, $wgOut, $wgUser;
2168
2169 $current = ( $oldid == $this->mLatest );
2170 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2171 $sk = $wgUser->getSkin();
2172 $lnk = $current
2173 ? wfMsg( 'currentrevisionlink' )
2174 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2175 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2176 $nextlink = $current
2177 ? wfMsg( 'nextrevision' )
2178 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2179 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2180 $wgOut->setSubtitle( $r );
2181 }
2182
2183 /**
2184 * This function is called right before saving the wikitext,
2185 * so we can do things like signatures and links-in-context.
2186 *
2187 * @param string $text
2188 */
2189 function preSaveTransform( $text ) {
2190 global $wgParser, $wgUser;
2191 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2192 }
2193
2194 /* Caching functions */
2195
2196 /**
2197 * checkLastModified returns true if it has taken care of all
2198 * output to the client that is necessary for this request.
2199 * (that is, it has sent a cached version of the page)
2200 */
2201 function tryFileCache() {
2202 static $called = false;
2203 if( $called ) {
2204 wfDebug( " tryFileCache() -- called twice!?\n" );
2205 return;
2206 }
2207 $called = true;
2208 if($this->isFileCacheable()) {
2209 $touched = $this->mTouched;
2210 $cache = new CacheManager( $this->mTitle );
2211 if($cache->isFileCacheGood( $touched )) {
2212 global $wgOut;
2213 wfDebug( " tryFileCache() - about to load\n" );
2214 $cache->loadFromFileCache();
2215 return true;
2216 } else {
2217 wfDebug( " tryFileCache() - starting buffer\n" );
2218 ob_start( array(&$cache, 'saveToFileCache' ) );
2219 }
2220 } else {
2221 wfDebug( " tryFileCache() - not cacheable\n" );
2222 }
2223 }
2224
2225 /**
2226 * Check if the page can be cached
2227 * @return bool
2228 */
2229 function isFileCacheable() {
2230 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2231 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2232
2233 return $wgUseFileCache
2234 and (!$wgShowIPinHeader)
2235 and ($this->getID() != 0)
2236 and ($wgUser->isAnon())
2237 and (!$wgUser->getNewtalk())
2238 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2239 and (empty( $action ) || $action == 'view')
2240 and (!isset($oldid))
2241 and (!isset($diff))
2242 and (!isset($redirect))
2243 and (!isset($printable))
2244 and (!$this->mRedirectedFrom);
2245 }
2246
2247 /**
2248 * Loads cur_touched and returns a value indicating if it should be used
2249 *
2250 */
2251 function checkTouched() {
2252 $fname = 'Article::checkTouched';
2253 if( !$this->mDataLoaded ) {
2254 $dbr =& $this->getDB();
2255 $data = $this->pageDataFromId( $dbr, $this->getId() );
2256 if( $data ) {
2257 $this->loadPageData( $data );
2258 }
2259 }
2260 return !$this->mIsRedirect;
2261 }
2262
2263 /**
2264 * Edit an article without doing all that other stuff
2265 * The article must already exist; link tables etc
2266 * are not updated, caches are not flushed.
2267 *
2268 * @param string $text text submitted
2269 * @param string $comment comment submitted
2270 * @param bool $minor whereas it's a minor modification
2271 */
2272 function quickEdit( $text, $comment = '', $minor = 0 ) {
2273 $fname = 'Article::quickEdit';
2274 wfProfileIn( $fname );
2275
2276 $dbw =& wfGetDB( DB_MASTER );
2277 $dbw->begin();
2278 $revision = new Revision( array(
2279 'page' => $this->getId(),
2280 'text' => $text,
2281 'comment' => $comment,
2282 'minor_edit' => $minor ? 1 : 0,
2283 ) );
2284 $revisionId = $revision->insertOn( $dbw );
2285 $this->updateRevisionOn( $dbw, $revision );
2286 $dbw->commit();
2287
2288 wfProfileOut( $fname );
2289 }
2290
2291 /**
2292 * Used to increment the view counter
2293 *
2294 * @static
2295 * @param integer $id article id
2296 */
2297 function incViewCount( $id ) {
2298 $id = intval( $id );
2299 global $wgHitcounterUpdateFreq;
2300
2301 $dbw =& wfGetDB( DB_MASTER );
2302 $pageTable = $dbw->tableName( 'page' );
2303 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2304 $acchitsTable = $dbw->tableName( 'acchits' );
2305
2306 if( $wgHitcounterUpdateFreq <= 1 ){ //
2307 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2308 return;
2309 }
2310
2311 # Not important enough to warrant an error page in case of failure
2312 $oldignore = $dbw->ignoreErrors( true );
2313
2314 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2315
2316 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2317 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2318 # Most of the time (or on SQL errors), skip row count check
2319 $dbw->ignoreErrors( $oldignore );
2320 return;
2321 }
2322
2323 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2324 $row = $dbw->fetchObject( $res );
2325 $rown = intval( $row->n );
2326 if( $rown >= $wgHitcounterUpdateFreq ){
2327 wfProfileIn( 'Article::incViewCount-collect' );
2328 $old_user_abort = ignore_user_abort( true );
2329
2330 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2331 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2332 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2333 'GROUP BY hc_id');
2334 $dbw->query("DELETE FROM $hitcounterTable");
2335 $dbw->query('UNLOCK TABLES');
2336 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2337 'WHERE page_id = hc_id');
2338 $dbw->query("DROP TABLE $acchitsTable");
2339
2340 ignore_user_abort( $old_user_abort );
2341 wfProfileOut( 'Article::incViewCount-collect' );
2342 }
2343 $dbw->ignoreErrors( $oldignore );
2344 }
2345
2346 /**#@+
2347 * The onArticle*() functions are supposed to be a kind of hooks
2348 * which should be called whenever any of the specified actions
2349 * are done.
2350 *
2351 * This is a good place to put code to clear caches, for instance.
2352 *
2353 * This is called on page move and undelete, as well as edit
2354 * @static
2355 * @param $title_obj a title object
2356 */
2357
2358 function onArticleCreate($title_obj) {
2359 global $wgUseSquid, $wgPostCommitUpdateList;
2360
2361 $title_obj->touchLinks();
2362 $titles = $title_obj->getLinksTo();
2363
2364 # Purge squid
2365 if ( $wgUseSquid ) {
2366 $urls = $title_obj->getSquidURLs();
2367 foreach ( $titles as $linkTitle ) {
2368 $urls[] = $linkTitle->getInternalURL();
2369 }
2370 $u = new SquidUpdate( $urls );
2371 array_push( $wgPostCommitUpdateList, $u );
2372 }
2373 }
2374
2375 function onArticleDelete($title_obj) {
2376 $title_obj->touchLinks();
2377 }
2378
2379 function onArticleEdit($title_obj) {
2380 // This would be an appropriate place to purge caches.
2381 // Why's this not in here now?
2382 }
2383
2384 /**#@-*/
2385
2386 /**
2387 * Info about this page
2388 * Called for ?action=info when $wgAllowPageInfo is on.
2389 *
2390 * @access public
2391 */
2392 function info() {
2393 global $wgLang, $wgOut, $wgAllowPageInfo;
2394 $fname = 'Article::info';
2395
2396 if ( !$wgAllowPageInfo ) {
2397 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2398 return;
2399 }
2400
2401 $page = $this->mTitle->getSubjectPage();
2402
2403 $wgOut->setPagetitle( $page->getPrefixedText() );
2404 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2405
2406 # first, see if the page exists at all.
2407 $exists = $page->getArticleId() != 0;
2408 if( !$exists ) {
2409 $wgOut->addHTML( wfMsg('noarticletext') );
2410 } else {
2411 $dbr =& $this->getDB( DB_SLAVE );
2412 $wl_clause = array(
2413 'wl_title' => $page->getDBkey(),
2414 'wl_namespace' => $page->getNamespace() );
2415 $numwatchers = $dbr->selectField(
2416 'watchlist',
2417 'COUNT(*)',
2418 $wl_clause,
2419 $fname,
2420 $this->getSelectOptions() );
2421
2422 $pageInfo = $this->pageCountInfo( $page );
2423 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2424
2425 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2426 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2427 if( $talkInfo ) {
2428 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2429 }
2430 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2431 if( $talkInfo ) {
2432 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2433 }
2434 $wgOut->addHTML( '</ul>' );
2435
2436 }
2437 }
2438
2439 /**
2440 * Return the total number of edits and number of unique editors
2441 * on a given page. If page does not exist, returns false.
2442 *
2443 * @param Title $title
2444 * @return array
2445 * @access private
2446 */
2447 function pageCountInfo( $title ) {
2448 $id = $title->getArticleId();
2449 if( $id == 0 ) {
2450 return false;
2451 }
2452
2453 $dbr =& $this->getDB( DB_SLAVE );
2454
2455 $rev_clause = array( 'rev_page' => $id );
2456 $fname = 'Article::pageCountInfo';
2457
2458 $edits = $dbr->selectField(
2459 'revision',
2460 'COUNT(rev_page)',
2461 $rev_clause,
2462 $fname,
2463 $this->getSelectOptions() );
2464
2465 $authors = $dbr->selectField(
2466 'revision',
2467 'COUNT(DISTINCT rev_user_text)',
2468 $rev_clause,
2469 $fname,
2470 $this->getSelectOptions() );
2471
2472 return array( 'edits' => $edits, 'authors' => $authors );
2473 }
2474
2475 /**
2476 * Return a list of templates used by this article.
2477 * Uses the links table to find the templates
2478 *
2479 * @return array
2480 */
2481 function getUsedTemplates() {
2482 $result = array();
2483 $id = $this->mTitle->getArticleID();
2484
2485 $db =& wfGetDB( DB_SLAVE );
2486 $res = $db->select( array( 'pagelinks' ),
2487 array( 'pl_title' ),
2488 array(
2489 'pl_from' => $id,
2490 'pl_namespace' => NS_TEMPLATE ),
2491 'Article:getUsedTemplates' );
2492 if ( false !== $res ) {
2493 if ( $db->numRows( $res ) ) {
2494 while ( $row = $db->fetchObject( $res ) ) {
2495 $result[] = $row->pl_title;
2496 }
2497 }
2498 }
2499 $db->freeResult( $res );
2500 return $result;
2501 }
2502 }
2503
2504 ?>